﻿Public Class Gestion_Localidades
    Enum estado
        inicial
        insertar
        modificar
    End Enum
    Dim operacion As estado = estado.inicial
    Dim id As String = ""
    Dim tratamiento As New Tratamiento_Objetos
    Dim datos As New datos
    Dim pk As String = "id_localidad"
    Dim nombre As String = "localidad"
    Dim nombre_tabla As String = "localidad"

    Private Sub botones(ByVal flag As Boolean)
        Me.btn_nuevo.Enabled = flag
        Me.btn_salir.Enabled = flag
        Me.btn_cancelar.Enabled = Not flag
        Me.btn_guardar.Enabled = Not flag
        Me.btn_eliminar.Enabled = Not flag
        Me.btn_modificar.Enabled = Not flag
    End Sub

    Private Function validar() As Boolean
        Dim flag As Boolean = True
        If String.IsNullOrEmpty(Me.txt_nombre.Text) Then
            lbl_nombre.ForeColor = Color.Red
            txt_nombre.Focus()
            flag = False
        Else
            lbl_nombre.ForeColor = Color.Black
        End If

        Return flag
    End Function

    Private Function validarUso() As Boolean
        Dim conexion As New SqlClient.SqlConnection
        Dim cmd As New SqlClient.SqlCommand
        Dim tabla As New Data.DataTable
        Dim consulta As String = "select * from barrio where " & pk & " = '" & id & "'"
        conexion.ConnectionString = datos._cadena
        conexion.Open()
        cmd.Connection = conexion
        cmd.CommandType = CommandType.Text
        cmd.CommandText = consulta
        tabla.Load(cmd.ExecuteReader())
        conexion.Close()
        If tabla.Rows.Count = 0 Then
            Return False
        Else
            Return True
        End If
    End Function

    Private Sub Gestion_Nacionalidad_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        botones(True)
        cargarGrilla()
        tratamiento.habilitar(False, Me.Controls)
        btn_nuevo.Focus()
    End Sub


    Private Sub DataGridView1_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
        Me.operacion = estado.modificar
        id = DataGridView1.CurrentRow.Cells("Id_localidad").Value
        Me.txt_nombre.Text = DataGridView1.CurrentRow().Cells("Descripcion").Value
        tratamiento.habilitar(True, Me.Controls)
        botones(False)
        Me.btn_guardar.Enabled = False
        tratamiento.labels_Color(Color.Black, Me.Controls)
    End Sub

    Private Sub Gestion_Cliente_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If operacion = estado.inicial Then
            If MessageBox.Show("¿Desea salir?", "Alerta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
                e.Cancel = True
            End If
        Else
            MessageBox.Show("Termine la operacion actual!", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            e.Cancel = True
        End If

    End Sub

    Private Sub cargarGrilla()
        Dim conexion As New SqlClient.SqlConnection
        Dim cmd As New SqlClient.SqlCommand
        Dim data As New Data.DataTable


        conexion.ConnectionString = datos._cadena
        conexion.Open()
        cmd.Connection = conexion
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "select * from " & nombre_tabla
        data.Load(cmd.ExecuteReader())
        conexion.Close()
        Dim fila As Integer = 0

        DataGridView1.Rows.Clear()

        For fila = 0 To data.Rows.Count - 1
            DataGridView1.Rows.Add()
            DataGridView1.Rows(fila).Cells("Id_localidad").Value = data.Rows(fila)(pk)
            DataGridView1.Rows(fila).Cells("Descripcion").Value = data.Rows(fila)("nombre")
        Next
    End Sub

    Private Function guardar() As Integer
        Dim conexion As New SqlClient.SqlConnection
        Dim cmd As New SqlClient.SqlCommand

        conexion.ConnectionString = datos._cadena
        conexion.Open()
        cmd.Connection = conexion
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "insert into " & nombre_tabla & "(nombre) values ('" & txt_nombre.Text & "')"
        Dim temporal As Integer = cmd.ExecuteNonQuery
        conexion.Close()
        Return temporal
    End Function

    Private Sub soloLetras(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_nombre.KeyPress
        If Not Char.IsLetter(e.KeyChar) And Not Char.IsWhiteSpace(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.KeyChar = ""
        End If
    End Sub

    Private Sub btn_nuevo_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_nuevo.Click
        operacion = estado.insertar
        botones(False)
        Me.btn_eliminar.Enabled = False
        Me.btn_modificar.Enabled = False
        tratamiento.habilitar(True, Me.Controls)
        Me.txt_nombre.Focus()
    End Sub

    Private Sub btn_guardar_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_guardar.Click
        If validar() = True Then
            If MessageBox.Show("¿Desea guardar la " & nombre & "?", "Confirmacion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                If guardar() = 1 Then
                    MessageBox.Show("Carga realizada con exito.", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    cargarGrilla()
                    operacion = estado.inicial
                Else
                    MessageBox.Show("Error al realizar la carga.", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
                tratamiento.limpiar(Me.Controls)
                tratamiento.habilitar(False, Me.Controls)
                botones(True)
                btn_nuevo.Focus()
            End If
        End If
    End Sub

    Private Sub btn_modificar_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_modificar.Click
        If validar() = True Then
            If MessageBox.Show("¿Desea modificar la " & nombre & "?", "Consulta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                Dim conexion As New SqlClient.SqlConnection
                Dim cmd As New SqlClient.SqlCommand
                Dim consulta As String = ""
                conexion.ConnectionString = datos._cadena
                conexion.Open()
                consulta = "update " & nombre_tabla
                consulta &= " set nombre = '" & Me.txt_nombre.Text & "'"
                consulta &= " where " & pk & " = " & id
                cmd.CommandType = CommandType.Text
                cmd.CommandText = consulta
                cmd.Connection = conexion
                Dim filas As Integer = cmd.ExecuteNonQuery()
                conexion.Close()

                If filas = 1 Then
                    MessageBox.Show("Modificacion realizada.", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    operacion = estado.inicial
                Else
                    MessageBox.Show("Error al modificar", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    operacion = estado.inicial
                End If

                cargarGrilla()
                tratamiento.limpiar(Me.Controls)
                tratamiento.habilitar(False, Me.Controls)
                operacion = estado.inicial
                botones(True)
            End If
        End If
    End Sub

    Private Sub btn_cancelar_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cancelar.Click
        If operacion = estado.insertar Then
            If MessageBox.Show("¿Desea cancelar la carga?", "Confirmacion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                tratamiento.limpiar(Me.Controls)
                tratamiento.habilitar(False, Me.Controls)
                tratamiento.labels_Color(Color.Black, Me.Controls)
                Me.btn_nuevo.Focus()
                botones(True)
                operacion = estado.inicial
            End If
        Else
            If MessageBox.Show("¿Desea cancelar la modificacion?", "Confirmacion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                tratamiento.limpiar(Me.Controls)
                tratamiento.habilitar(False, Me.Controls)
                tratamiento.labels_Color(Color.Black, Me.Controls)
                Me.btn_nuevo.Focus()
                botones(True)
                operacion = estado.inicial
            End If
        End If
    End Sub

    Private Sub btn_eliminar_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_eliminar.Click
        If MessageBox.Show("¿Desea eliminar la " & nombre & "?", "Pregunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            If validarUso() = False Then
                Dim conexion As New SqlClient.SqlConnection
                Dim cmd As New SqlClient.SqlCommand
                Dim consulta As String = "delete from " & nombre_tabla & " where " & pk & " = '" & id & "'"

                conexion.ConnectionString = datos._cadena
                conexion.Open()
                cmd.Connection = conexion
                cmd.CommandType = CommandType.Text
                cmd.CommandText = consulta
                Dim filas As Integer = cmd.ExecuteNonQuery()
                conexion.Close()
                If filas = 1 Then
                    MessageBox.Show("Eliminacion realizada.", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    cargarGrilla()
                    operacion = estado.inicial
                Else
                    MessageBox.Show("Error al eliminar", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    operacion = estado.inicial
                End If
                tratamiento.limpiar(Me.Controls)
                tratamiento.habilitar(False, Me.Controls)
                botones(True)
            Else
                MessageBox.Show("Existen barrios usando esta " & nombre & ". Elimine los barrios.", "Informacion", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        End If
    End Sub

    Private Sub btn_salir_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_salir.Click
        Close()
    End Sub
End Class